<template>
  <div class="index">
    <v-header></v-header>
    <div class="topMsg">
      <div class="left">
        <p>结算页</p>
        <p>现金账户金额<span>￥{{balance}}</span>元</p>
      </div>
      <div class="right"><p @click="goOrder">我的订单</p></div>
    </div>
    <div class="content">

      <div class="address">
        <div class="tit" style="display:flex;justify-content:space-between;">
          <p>收货地址：</p>
          <p @click="addAddress" style="font-size:14px;color:#66b1ff;text-decoration:underline;cursor:pointer;">新增地址</p>
        </div>
        <div class="addList">
          <!-- <el-radio-group v-model="radio"> -->
            <div class="item" v-for="(item,index) in addresslist">
              <el-radio style="width:50px;" v-model="radio" :label="item.id" @change="changeAddress">-</el-radio>
              <p style="width:80px;">{{item.receiver}}</p>
              <p style="width:100px;">{{item.telephone}}</p>
              <p style="width:200px;">{{item.province_name}}/{{item.city_name}}/{{item.district_name}}/{{item.area_name}}</p>
              <p style="width:200px;">{{item.address}}</p>
              <el-button type="danger" @click="delAddress(item.id)">删除地址</el-button>
            </div>
          <!-- </el-radio-group> -->
        </div>
        <el-dialog
          title="新增地址"
          :visible.sync="dialogVisible"
          :close-on-click-modal="false">
            <el-form ref="form"  :rules="rules" :model="form" label-width="140px" style="margin-top:30px;">
              <el-form-item label="收货人姓名" prop="consignee">
                <el-input v-model="form.consignee" placeholder="请输入收货人姓名"></el-input>
              </el-form-item>
              <el-form-item label="收货人手机号" prop="telephone">
                <el-input v-model="form.telephone" placeholder="请输入收货人手机号"></el-input>
              </el-form-item>

              <el-form-item label="收货地址">
                <el-row>
                  <el-col :span="6">
                    <el-form-item prop="province_id">
                      <el-select v-model="form.province_id" clearable placeholder="请选择省" @change="getRegion($event, 'city', provinceList.find(item => { return item.region_id === $event}))">
                        <el-option :label="item.region_name" :value="item.region_id" v-for="item in provinceList"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" v-if="form.province_id" >
                    <el-form-item prop="city_id">
                      <el-select v-model="form.city_id" clearable placeholder="请选择市"  @change="getRegion($event, 'district', cityList.find(item => { return item.region_id === $event}))">
                        <el-option :label="item.region_name" :value="item.region_id" v-for="item in cityList"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" v-if="form.city_id">
                    <el-form-item prop="district_id">
                      <el-select v-model="form.district_id" clearable placeholder="请选择区" @change="getRegion($event, 'area', districtList.find(item => { return item.region_id === $event}))">
                        <el-option :label="item.region_name" :value="item.region_id" v-for="item in districtList"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" v-if="form.district_id">
                    <el-form-item prop="area_id">
                      <el-select v-model="form.area_id" clearable placeholder="请选择街道" @change="getRegion($event, '', areaList.find(item => { return item.region_id === $event}))">
                        <el-option :label="item.region_name" :value="item.region_id" v-for="item in areaList"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="详细收货地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入收货人详细地址"></el-input>
              </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addBtn">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <div class="goodsList">
        <div class="tit">
          <p>商品清单：</p>
        </div>
        <div class="msg">
          <!-- <p class="back">返回进货单</p> -->
          <div class="list">
            <div class="goodItem" v-for="item in $store.state.selectList" v-if="item.count">
              <div class="left">
                <img :src="item.img_url">
                <p>{{item.goods_name}}</p>
                <p>￥{{item.discount_price}}*{{item.count}}</p>
              </div>
              <p>￥{{item.discount_price * item.count}}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="msg">
        <p>运费： <span>{{shipment.toFixed(2)}}</span>元</p>
        <p>商品总额：<span>{{price.toFixed(2)}}</span>元</p>
        <p>应付总额：<span>{{(parseFloat(price.toFixed(2))+parseFloat(shipment.toFixed(2))).toFixed(2)}}</span>元</p>
      </div>
    </div>
    <div class="submit">
      <p @click="create">提交订单</p>
    </div>
  </div>
</template>
<script>
  import header from '../common/header'
  import {region, create, balance, stock,addressList,deladdress,addAddress} from '../../api/ajax'
  import md5 from 'js-md5';//md5加密
  export default{
    data(){
      return{
        form: {
          consignee: '',
          telephone: '',
          province_id: '',
          city_id: '',
          district_id: '',
          area_id: '',
          address: '',
          address_id:'',
          area_name: '',
          city_name: '',
          district_name: '',
          province_name: '',
        },
        params:{},
        provinceList: [],
        cityList: [],
        districtList: [],
        areaList: [],
        shipment: 0,
        price: 0,
        balance: 0,
        rules: {
          consignee: [
            { required: true, message: '请输入收货人姓名', trigger: 'blur' },
          ],
          telephone: [
            { required: true, message: '请输入收货人手机号', trigger: 'blur' },
          ],
          province_id: [
            { required: true, message: '请选择省', trigger: 'blur' },
          ],
          city_id: [
            { required: true, message: '请选择市', trigger: 'blur' },
          ],
          district_id: [
            { required: true, message: '请选择区', trigger: 'blur' },
          ],
          area_id: [
            { required: true, message: '请选择街道', trigger: 'blur' },
          ],
          address: [
            { required: true, message: '请输入详细收货地址', trigger: 'blur' },
          ],
        },
        addresslist:[],
        radio:'',
        dialogVisible:false
      }
    },
    components: {'v-header': header},
    watch: {
      '$store.state.selectList': {
        handler(newName, oldName) {
          let newShipment = 0;
          let newPrice = 0
          newName.forEach(item => {
            if (item.count) {
              let itemShipment = (Number(item.count) * Number(item.shipment))
              let itemPrice = (Number(item.count) * Number(item.discount_price))
              newPrice += itemPrice
              newShipment += itemShipment
            }
          })
          this.shipment=newShipment
          this.price=newPrice
        },
        deep: true,
        immediate: true
      }
    },
    mounted(){
      this.getRegion(1, 'province');
      this.getBalance();
      this.getAddList();
    },
    methods: {
      addBtn(){
        this.$refs.form.validate((valid) => {
          if (valid) {
            console.log(this.form);
            let params = {
              receiver: this.form.consignee,
              telephone: this.form.telephone,
              province_id: this.form.province_id,
              city_id: this.form.city_id,
              district_id: this.form.district_id,
              area_id: this.form.area_id,
              address: this.form.address,
              address_id: this.form.address_id,
              area_name: this.form.area_name,
              city_name: this.form.city_name,
              district_name: this.form.district_name,
              province_name: this.form.province_name
            }
            addAddress(params).then(res => {
              console.log(res);
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              this.dialogVisible = false;
              this.getAddList();
            })
          }
        })
      },
      delAddress(id){
        this.$confirm('是否删除地址?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deladdress({
            address_id:id
          }).then(res => {
            console.log(res);
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getAddList();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      addAddress(){
        this.dialogVisible = true;
        this.form = {
          consignee: '',
          telephone: '',
          province_id: '',
          city_id: '',
          district_id: '',
          area_id: '',
          address: '',
          address_id:'',
          area_name: '',
          city_name: '',
          district_name: '',
          province_name: '',
        }
      },
      changeAddress(){
        let id = this.radio;
        let el;
        this.addresslist.forEach(function(element) {
          if(id == element.id){
            el = element;
          }
        })
        this.params.address = el.address;
        this.params.area_id = el.area_id;
        this.params.city_id = el.city_id;
        this.params.consignee = el.receiver;
        this.params.district_id = el.district_id;
        this.params.area_name = el.area_name;
        this.params.city_name = el.city_name;
        this.params.district_name = el.district_name;
        this.params.province_name = el.province_name;
        this.params.province_id = el.province_id;
        this.params.telephone = el.telephone;
        this.params.address_id = el.id;
      },
      getAddList(){
        addressList().then(res => {
          console.log(res);
          this.addresslist = res.data.data;
        })
      },
      getRegion(e, type,obj) {
        console.log(obj)
        region({
          parent: e,
        }).then(res => {
          if (res.data.code === 1) {
            if (type === 'province') {
              for (let i in res.data.data.regions) {
                this.provinceList.push(res.data.data.regions[i]);
              }
              this.form.city_id = '';
              this.form.district_id = '';
              this.form.area_id = '';
            }
            if (type === 'city') {
              for (let i in res.data.data.regions) {
                this.cityList.push(res.data.data.regions[i]);
              }
              this.form.city_id = '';
              this.form.district_id = '';
              this.form.area_id = '';
              this.form.province_name = obj.region_name;
            }
            if (type === 'district') {
              for (let i in res.data.data.regions) {
                this.districtList.push(res.data.data.regions[i]);
              }
              this.form.district_id = '';
              this.form.area_id = '';
              this.form.city_name = obj.region_name;
            }
            if (type === 'area') {
              for (let i in res.data.data.regions) {
                this.areaList.push(res.data.data.regions[i]);
              }
              this.form.area_id = '';
              this.form.district_name = obj.region_name;
            } else {
              this.form.area_name = obj.region_name;

            }
          }
        })
      },
      create() {
        // this.$refs.form.validate((valid) => {
          // if (valid) {
            if(this.radio == ''){
              this.$message({
                type: 'error',
                message: '请选择地址!'
              })
            }else{
              let goods_items = []
            let goods_all_info = []
            let goods_ids = []
            this.$store.state.selectList.forEach(item => {
              if (item.count) {
                goods_items.push({
                  goods_id: item.goods_id,
                  count: item.count
                })
                goods_all_info.push({
                  goods_id: item.goods_id,
                  goods_name: item.goods_name,
                  goods_num: item.count,
                  goods_price: item.discount_price,
                  goods_img: item.img_url,
                  count: item.count
                })
                goods_ids.push(item.goods_id)
              }
            });
            const {address, area_id, city_id, consignee, district_id, province_id,telephone, area_name, city_name, district_name,province_name,address_id} = this.params;
            stock({
              goods_ids: goods_ids.join(','),
              goods_items: JSON.stringify(goods_items),
              province_id,
              city_id,
              district_id,
              area_id,
            }).then(res => {
              if (res.data.code) {
                create({
                  address,
                  area_id,
                  city_id,
                  consignee,
                  district_id,
                  area_name,
                  city_name,
                  address_id,
                  district_name,
                  province_name,
                  goods_amount: this.price,
                  goods_items: JSON.stringify(goods_items),
                  goods_all_info: JSON.stringify(goods_all_info),
                  province_id,
                  shipment_expense_amount: this.shipment,
                  telephone,
                }).then(res => {
                  console.log(res)
                  if (res.data.code) {
                    this.$router.push({
                      name: 'myOrder'
                    });
                    this.$message.success('下单成功')
                  }
                })
              }
            })
            }
            

          // }
        // });
      },
      getBalance () {
        balance({}).then(res => {
          if (res.data.code === 1) {
            this.balance = res.data.data.balance
          }
        })
      },
      goOrder () {
        this.$router.push({
          name: 'personalCenter'
        })
      },
    },
  };
</script>
<style scoped>
.addList{
  width: 100%;
  margin-top: 30px;
}
.addList .item{
  border-radius: 4px;
  border: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 40px;
  margin-bottom: 10px;
}
.submit{
  width: 1200px;
  margin:0 auto;
  display: flex;
  justify-content: flex-end;
}
.submit p{
  width: 100px;
  height: 35px;
  background: #409EFF;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 6px;
  margin-top: 20px;
  margin-bottom: 100px;
  cursor: pointer;
}
.bottom .msg p{
  font-size: 16px;
  line-height: 30px;
  color: #333;
}
.bottom .msg p span{
  color: #ff6666;
}
.bottom{
  width: 1200px;
  margin:0 auto;
  display: flex;
  align-items: center;
  margin-top: 20px;
  justify-content: flex-end;
}
.otherMsg{
  padding: 20px;
}
.otherMsg .msg{
  display: flex;
  align-items: center;
  margin-top: 20px;
}
.otherMsg .msg p{
  font-size: 16px;
  line-height: 16px;
  color: #333;
}
.otherMsg .msg input{
  flex: 1;
  width: 100%;
  margin-left: 20px;
  height: 50px;
  padding-left: 20px;
  font-size: 16px;
  line-height: 16px;
  color: #333;
  border:1px solid #eaeaea;
}
.otherMsg .tit{
  font-size: 24px;
  line-height: 24px;
  color: #333;
}
  .bill .msg{
    margin-left: 130px;
    margin-top: 20px;
  }
  .bill .msg p{
    font-size: 16px;
    line-height: 30px;
    color: #333;
  }
  .bill{
    padding: 20px;
  }
  .bill .tit{
    font-size: 24px;
    line-height: 24px;
    color: #333;
  }
.content .goodsList .msg .list .goodItem p:nth-child(2){
  font-size: 16px;
  line-height: 16px;
  color: #333;
  margin-left: 150px;
}
.content .goodsList .msg .list .goodItem p:nth-child(3){
  font-size: 16px;
  line-height: 16px;
  color: #333;
  margin-left: 300px;
}
.content .goodsList .msg .list .goodItem p:nth-child(4){
  font-size: 16px;
  line-height: 16px;
  color: #333;
  margin-left: 100px;
}
.content .goodsList .msg .list .goodItem img{
  width: 80px;
  height: 80px;
  border: 1px solid #eaeaea;
}
.content .goodsList .msg .list .goodItem .left{
  display: flex;
  align-items: center;
  /*justify-content: */
}
.content .goodsList .msg .list .goodItem{
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid #eaeaea;
  padding: 20px;
  margin-top: 20px;
}
  .content .goodsList .msg .back{
    font-size: 16px;
    line-height: 16px;
    color: #66b1ff;
    display: flex;
    justify-content: flex-end;
    text-decoration: underline;
    cursor: pointer;
  }
  .content .goodsList{
    padding: 20px;
  }
 .content .address{
  padding: 20px;
 }
 .content .address .tit,.content .goodsList .tit{
  font-size: 24px;
  line-height: 24px;
  color: #333;
 }
 .content .address .msg{
  margin-top: 20px;
  padding-left: 130px;
 }
 .content .address .msg p:nth-child(1){
  font-size: 16px;
  line-height: 24px;
  color: #333;
 }
 .content .address .msg p:nth-child(2){
  font-size: 16px;
  line-height: 34px;
  color: #333;
 }
 .content .address .msg p:nth-child(3){
  font-size: 16px;
  line-height: 24px;
  color: #999;
 }

  .content{
    width: 1200px;
    margin: 0 auto;
    border:1px solid #eaeaea;
    margin-top: 20px;
  }
  .topMsg{
    width: 1200px;
    height: 50px;
    margin: 0 auto;
    border: 1px solid #eaeaea;
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .topMsg .left{
    display: flex;
    align-items: flex-end;
  }
  .topMsg .left p:nth-child(1){
    font-size: 20px;
    line-height: 20px;
    color: #333;
    margin-left: 20px;
  }
  .topMsg .left p:nth-child(2){
    font-size: 16px;
    line-height: 16px;
    color: #333;
    margin-left: 20px;
  }
  .topMsg .left p:nth-child(2) span{
    color: #ff6666;
  }
  .topMsg .right{
    font-size: 16px;
    line-height: 16px;
    color: #66b1ff;
    margin-right: 20px;
    cursor: pointer;
    text-decoration: underline;
  }
</style>
